import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import math
import webbrowser
import requests
from io import BytesIO
from PIL import Image, ImageTk

class CalculatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("金融计算器应用")
        self.root.geometry("900x580")
        self.root.resizable(True, True)
        self.root.configure(bg="#ffffff")
        self.root.attributes("-alpha", 0.95)

        # 创建所有页面的容器
        self.container = tk.Frame(root)
        self.container.pack(fill=tk.BOTH, expand=True)

        # 创建各个页面
        self.main_page = MainPage(self.container, self)
        self.insurance_page = InsuranceCalculator(self.container, self)
        self.mortgage_page = MortgageCalculator(self.container, self)

        # 显示主页面
        self.show_main_page()

    def show_main_page(self):
        self.main_page.frame.pack(fill=tk.BOTH, expand=True)
        self.insurance_page.frame.pack_forget()
        self.mortgage_page.frame.pack_forget()

    def show_insurance_calculator(self):
        self.main_page.frame.pack_forget()
        self.insurance_page.frame.pack(fill=tk.BOTH, expand=True)
        self.mortgage_page.frame.pack_forget()

    def show_mortgage_calculator(self):
        self.main_page.frame.pack_forget()
        self.insurance_page.frame.pack_forget()
        self.mortgage_page.frame.pack(fill=tk.BOTH, expand=True)


class MainPage:
    def __init__(self, parent, app):
        self.frame = tk.Frame(parent)
        self.app = app
        self.parent = parent

        # 创建背景画布用于显示半透明图片
        self.background_canvas = tk.Canvas(self.frame)
        self.background_canvas.pack(fill=tk.BOTH, expand=True)

        # 加载金融背景图片（高楼大厦）
        self.load_background_image()

        # 创建半透明遮罩层，让文字更清晰
        self.background_canvas.create_rectangle(
            0, 0, 1000, 800,
            fill="#ffffff",
            stipple="gray50"  # 半透明效果
        )

        # 页面标题
        # title_label = tk.Label(
        #     self.background_canvas,
        #     text="A.C金融计算器",
        #     font=("Arial", 20, "bold"),
        #     bg="systemTransparent",
        #     fg="#DB0011",
        #     highlightthickness = 0,
        #     bd = 0
        # )
        # self.background_canvas.create_window(450, 100, window=title_label)
        self.background_canvas.create_text(
            450, 100,  # 文字位置
            text="A.C金融计算器",
            font=("Arial", 20, "bold"),
            fill="#DB0011"  # 文字颜色
        )
        # 按钮容器，用于居中显示按钮
        button_frame = tk.Frame(self.background_canvas, bg=self.background_canvas["bg"],highlightthickness=0, bd=0 )
        self.background_canvas.create_window(450, 300, window=button_frame)

        # 创建渐变蓝色按钮样式
        self.style = ttk.Style()
        self.style.configure(
            "Gradient.TButton",
            font=("Arial", 14, "bold"),
            padding=20
        )

        # 保费计算器按钮
        self.create_gradient_button(
            button_frame,
            "保费计算器",
            self.app.show_insurance_calculator
        ).pack(pady=20)

        # 房贷计算器按钮
        self.create_gradient_button(
            button_frame,
            "房贷计算器",
            self.app.show_mortgage_calculator
        ).pack(pady=20)

        # 绑定窗口大小变化事件
        self.frame.bind("<Configure>", self.on_resize)

    def load_background_image(self):
        try:
            # 金融高楼大厦背景图片URL
            image_url = "https://copyright.bdstatic.com/vcg/creative/afa01b285c8964df08ce7b949eec4a69.jpg@h_1280"
            # 下载图片
            response = requests.get(image_url)
            img_data = BytesIO(response.content)

            # 打开并转换图片
            self.bg_image = Image.open(img_data)
            self.bg_photo = ImageTk.PhotoImage(self.bg_image)

            # 在画布上显示图片
            self.bg_image_id = self.background_canvas.create_image(0, 0,
                                                                   image=self.bg_photo,
                                                                   anchor=tk.NW)
        except Exception as e:
            print(f"无法加载背景图片: {e}")
            # 加载失败时使用纯色背景
            self.background_canvas.config(bg="#f0f8ff")

    def create_gradient_button(self, parent, text, command):
        """创建渐变蓝色按钮"""
        # 创建按钮容器
        btn_frame = tk.Frame(parent, bd=0, highlightthickness=0)

        # 创建渐变效果的画布
        btn_canvas = tk.Canvas(
            btn_frame,
            width=200,
            height=60,
            bd=0,
            highlightthickness=0,
            relief=tk.FLAT,
            cursor="hand2"
        )
        btn_canvas.pack()

        # 绘制渐变背景 (从浅蓝到深蓝)
        for i in range(200):
            color = f"#{int(173 - i * 0.3):02x}{int(216 - i * 0.1):02x}{int(230 + i * 0.1):02x}"
            btn_canvas.create_line(i, 0, i, 60, fill=color, width=1)

        # 创建按钮文字
        btn_canvas.create_text(
            100, 30,
            text=text,
            font=("Arial", 14, "bold"),
            fill="#ffffff"
        )

        # 绑定点击事件
        btn_canvas.bind("<Button-1>", lambda e: command())

        # 添加悬停效果
        def on_enter(e):
            btn_frame.config(bg="#1e90ff")

        def on_leave(e):
            btn_frame.config(bg="#ffffff")

        btn_frame.bind("<Enter>", on_enter)
        btn_frame.bind("<Leave>", on_leave)

        return btn_frame

    def on_resize(self, event):
        """窗口大小变化时调整背景图片"""
        if hasattr(self, 'bg_image') and event.width > 1 and event.height > 1:
            # 调整图片大小以适应窗口
            resized_image = self.bg_image.resize((event.width, event.height), Image.LANCZOS)
            self.bg_photo = ImageTk.PhotoImage(resized_image)
            self.background_canvas.itemconfig(self.bg_image_id, image=self.bg_photo)
            # 调整遮罩层大小
            self.background_canvas.coords(self.background_canvas.find_withtag("rectangle"),
                                          0, 0, event.width, event.height)

class InsuranceCalculator:
    def __init__(self, parent, app):
        self.app = app
        self.frame = tk.Frame(parent, bg="#ffffff")

        self.colors = {
            "primary_red": "#DB0011",
            "secondary_red": "#E60028",
            "light_red": "#FFF0F0",
            "white": "#ffffff",
            "text": "#333333",
            "border": "#DB0011",
            "gray": "#F5F5F5",
            "link": "#0000EE"  # 链接蓝色
        }

        self.fonts = {
            "title": ("Arial", 16, "bold"),
            "subtitle": ("Arial", 11, "bold"),
            "normal": ("Arial", 10),
            "small": ("Arial", 9),
            "link": ("Arial", 9, "underline")
        }

        self.selected_insurance = tk.StringVar()
        self.input_fields = {}

        self.main_frame = tk.Frame(self.frame, bg=self.colors["white"],
                                   highlightbackground=self.colors["border"],
                                   highlightthickness=1)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=2)

        # 添加返回按钮到左上角
        back_btn = tk.Button(
            self.main_frame,
            text="返回主页面",
            command=self.app.show_main_page,
            bg=self.colors["light_red"],
            fg=self.colors["primary_red"],
            font=self.fonts["small"],
            padx=5,
            pady=1
        )
        back_btn.pack(side=tk.TOP, anchor=tk.NW, padx=5, pady=5)

        # 创建标题信息
        self.create_header()
        # 创建产品选择
        self.create_insurance_selector()
        # 创建动态字段区域
        self.input_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        self.input_frame.pack(fill=tk.BOTH, expand=True, pady=2)

        # 创建评估按钮
        self.button_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        self.button_frame.pack(fill=tk.X, pady=2)
        self.evaluate_btn = tk.Button(
            self.button_frame,
            text="评估保费",
            command=self.calculate_premium,
            bg=self.colors["primary_red"],
            fg=self.colors["white"],
            font=self.fonts["subtitle"],
            padx=15,
            pady=1,
            relief=tk.RAISED,
            bd=1
        )
        self.evaluate_btn.pack(side=tk.RIGHT)

        # 创建结果区域
        self.result_frame = tk.LabelFrame(
            self.main_frame,
            text="保费评估结果",
            bg=self.colors["white"],
            fg=self.colors["primary_red"],
            font=self.fonts["subtitle"],
            highlightbackground=self.colors["border"],
            highlightthickness=1,
            bd=0
        )
        self.result_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)

        self.result_text = scrolledtext.ScrolledText(
            self.result_frame,
            bg=self.colors["white"],
            font=self.fonts["normal"],
            wrap=tk.WORD,
            relief=tk.FLAT,
            highlightthickness=0,
            padx=15,
            pady=1
        )
        self.result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=1)
        self.result_text.insert(tk.END, "请选择保险类型并填写相关信息，然后点击'评估保费'按钮查看结果...")
        self.result_text.config(state=tk.DISABLED)

        self.update_input_fields()

    # 原保险计算器的其他方法保持不变
    def create_header(self):
        header_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        header_frame.pack(fill=tk.X)

        title_label = tk.Label(
            header_frame,
            text="保险保费评估",
            font=self.fonts["title"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        title_label.pack(side=tk.LEFT, padx=5, pady=1)

        # 创建logo，Antinio.Chan（AC）
        logo_frame = tk.Frame(header_frame, width=800, height=60, bg=self.colors["white"])
        logo_frame.pack(side=tk.RIGHT, padx=(1, 0), pady=1)

        canvas = tk.Canvas(logo_frame, width=100, height=80, bg=self.colors["white"], highlightthickness=0)
        canvas.pack(fill=tk.BOTH, expand=True)

        center_x, center_y = 40, 30
        radius = 25

        points = []
        for i in range(6):
            angle_rad = math.pi / 3 * (i + 0.5)
            x = center_x + radius * math.cos(angle_rad)
            y = center_y + radius * math.sin(angle_rad)
            points.append(x)
            points.append(y)

        canvas.create_polygon(points, fill=self.colors["primary_red"], outline="", width=2)
        canvas.create_text(center_x, center_y, text="A.C", fill=self.colors["white"],
                           font=("Arial", 12, "bold"))

    def create_insurance_selector(self):
        selector_frame = tk.Frame(
            self.main_frame,
            bg=self.colors["light_red"],
            highlightbackground=self.colors["border"],
            highlightthickness=0.1
        )
        selector_frame.pack(fill=tk.X, pady=(0, 1), ipady=8)

        tk.Label(
            selector_frame,
            text="请选择保险类型:",
            font=self.fonts["normal"],
            bg=self.colors["light_red"],
            fg=self.colors["text"]
        ).pack(side=tk.LEFT, padx=15)

        insurance_types = ["人寿险", "健康险", "财产险", "车险"]
        self.selected_insurance.set(insurance_types[0])

        insurance_menu = ttk.Combobox(
            selector_frame,
            textvariable=self.selected_insurance,
            values=insurance_types,
            font=self.fonts["normal"],
            state="readonly",
            width=20
        )
        insurance_menu.pack(side=tk.LEFT, padx=10)
        insurance_menu.bind("<<ComboboxSelected>>", lambda event: self.update_input_fields())
        # 添加IFRS17链接
        link_frame = tk.Frame(selector_frame, bg=self.colors["white"])
        link_frame.pack(fill=tk.X, pady=(0, 10), anchor=tk.E)

        self.ifrs17_link = tk.Label(
            link_frame,
            text="想了解IFRS17？",
            font=self.fonts["link"],
            fg=self.colors["link"],
            bg=self.colors["white"],
            cursor="hand2"
        )
        self.ifrs17_link.pack(side=tk.RIGHT, padx=5, pady=5)
        self.ifrs17_link.bind("<Button-1>", self.open_ifrs17_link)
        self.ifrs17_link.bind("<Enter>", self.on_link_enter)
        self.ifrs17_link.bind("<Leave>", self.on_link_leave)

    def update_input_fields(self):
        for widget in self.input_frame.winfo_children():
            widget.destroy()

        self.input_fields.clear()
        insurance_type = self.selected_insurance.get()

        frame_title = tk.Label(
            self.input_frame,
            text=f"{insurance_type}信息填写",
            font=self.fonts["normal"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        frame_title.pack(anchor=tk.W, padx=10, pady=(0, 1))

        form_frame = tk.Frame(self.input_frame, bg=self.colors["white"])
        form_frame.pack(fill=tk.BOTH, expand=True, padx=10)

        if insurance_type == "人寿险":
            self.create_life_insurance_fields(form_frame)
        elif insurance_type == "健康险":
            self.create_health_insurance_fields(form_frame)
        elif insurance_type == "财产险":
            self.create_property_insurance_fields(form_frame)
        elif insurance_type == "车险":
            self.create_car_insurance_fields(form_frame)

        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, "请填写相关信息，然后点击'评估保费'按钮查看结果...")
        self.result_text.config(state=tk.DISABLED)

    def open_ifrs17_link(self, event):
        ifrs17_url = "https://www.ifrs.org/issued-standards/list-of-standards/ifrs-17-insurance-contracts/"
        webbrowser.open_new(ifrs17_url)

    def on_link_enter(self, event):
        self.ifrs17_link.config(fg=self.colors["secondary_red"])

    def on_link_leave(self, event):
        self.ifrs17_link.config(fg=self.colors["link"])

    def create_life_insurance_fields(self, parent):
        fields = [
            {"label": "年龄:", "type": "entry", "name": "age", "validation": "number", "required": True},
            {"label": "保险金额(万元):", "type": "entry", "name": "amount", "validation": "number", "required": True},
            {"label": "性别:", "type": "option", "name": "gender", "options": ["男", "女"], "required": True},
            {"label": "职业:", "type": "option", "name": "occupation",
             "options": ["办公室职员", "销售", "体力劳动者", "高空作业", "危险行业"], "required": True},
            {"label": "保险期限(年):", "type": "option", "name": "term",
             "options": ["10", "20", "30", "至60岁", "至70岁", "终身"], "required": True},
            {"label": "是否吸烟:", "type": "option", "name": "smoker", "options": ["是", "否"], "required": True},
            {"label": "健康状况:", "type": "option", "name": "health",
             "options": ["优秀", "良好", "一般", "较差", "有既往病史"], "required": True}
        ]
        self._create_input_form(parent, fields, fields_per_row=2)

    def create_property_insurance_fields(self, parent):
        fields = [
            {"label": "财产类型:", "type": "option", "name": "property_type",
             "options": ["住宅", "商铺", "办公楼", "厂房", "其他"], "required": True},
            {"label": "财产估值(万元):", "type": "entry", "name": "value", "validation": "number", "required": True},
            {"label": "所在地区:", "type": "option", "name": "location",
             "options": ["一线城市", "二线城市", "三线城市", "四线及以下城市", "农村地区"], "required": True},
            {"label": "建筑年代:", "type": "option", "name": "construction_year",
             "options": ["5年以内", "5-10年", "10-20年", "20年以上"], "required": True},
            {"label": "保障范围:", "type": "multiple", "name": "coverage",
             "options": ["火灾", "水灾", "盗窃", "第三方责任"], "required": True}
        ]
        self._create_input_form(parent, fields, fields_per_row=2)

    def create_health_insurance_fields(self, parent):
        fields = [
            {"label": "年龄:", "type": "entry", "name": "age", "validation": "number", "required": True},
            {"label": "保险金额(万元):", "type": "entry", "name": "amount", "validation": "number", "required": True},
            {"label": "性别:", "type": "option", "name": "gender", "options": ["男", "女"], "required": True},
            {"label": "职业:", "type": "option", "name": "occupation",
             "options": ["办公室职员", "销售", "体力劳动者", "高空作业", "危险行业"], "required": True},
            {"label": "既往病史:", "type": "option", "name": "medical_history",
             "options": ["无", "轻微疾病", "慢性疾病", "重大疾病史"], "required": True},
            {"label": "是否有社保:", "type": "option", "name": "social_security",
             "options": ["有", "无"], "required": True},
            {"label": "保障范围:", "type": "multiple", "name": "coverage",
             "options": ["住院医疗", "门诊医疗", "重大疾病", "意外伤害"], "required": True},
        ]
        self._create_input_form(parent, fields, fields_per_row=2)

    def create_car_insurance_fields(self, parent):
        fields = [
            {"label": "车辆类型:", "type": "option", "name": "car_type",
             "options": ["小型轿车", "SUV", "面包车", "货车", "豪华车"], "required": True},
            {"label": "购置价格(万元):", "type": "entry", "name": "price", "validation": "number", "required": True},
            {"label": "使用年限(年):", "type": "entry", "name": "car_age", "validation": "number", "required": True},
            {"label": "车辆用途:", "type": "option", "name": "usage",
             "options": ["私家车", "公务车", "营运车辆"], "required": True},
            {"label": "车主年龄:", "type": "entry", "name": "owner_age", "validation": "number", "required": True},
            {"label": "驾驶年限(年):", "type": "entry", "name": "driving_years", "validation": "number",
             "required": True},
            {"label": "近3年理赔次数:", "type": "option", "name": "claims",
             "options": ["0次", "1次", "2次", "3次及以上"], "required": True}
        ]
        self._create_input_form(parent, fields, fields_per_row=3)

    def _create_input_form(self, parent, fields, fields_per_row=2):
        for widget in parent.winfo_children():
            widget.destroy()

        for col in range(fields_per_row):
            parent.columnconfigure(col, weight=1)

        for i, field in enumerate(fields):
            row = i // fields_per_row
            col = i % fields_per_row

            field_frame = tk.Frame(parent, bg=self.colors["white"])
            field_frame.grid(row=row, column=col, padx=5, pady=2, sticky=tk.W + tk.E)

            label_text = field["label"]
            if field.get("required", False):
                label_text += " *"

            tk.Label(
                field_frame,
                text=label_text,
                font=self.fonts["small"],
                bg=self.colors["white"],
                fg=self.colors["text"],
                anchor=tk.W,
                wraplength=150
            ).pack(anchor=tk.W, pady=(0, 2))

            if field["type"] == "entry":
                entry = tk.Entry(
                    field_frame,
                    font=self.fonts["small"],
                    width=25,
                    highlightbackground=self.colors["border"],
                    highlightthickness=1
                )
                entry.pack(fill=tk.X)
                self.input_fields[field["name"]] = {
                    "widget": entry,
                    "type": "entry",
                    "required": field.get("required", False)
                }

                if field.get("validation") == "number":
                    validate_cmd = (self.frame.register(self.validate_number), '%P')
                    entry.config(validate="key", validatecommand=validate_cmd)

            elif field["type"] == "option":
                var = tk.StringVar()
                var.set(field["options"][0])
                option_menu = tk.OptionMenu(field_frame, var, *field["options"])
                option_menu.config(
                    font=self.fonts["small"],
                    width=25,
                    bg=self.colors["white"],
                    activebackground=self.colors["light_red"],
                    highlightbackground=self.colors["border"],
                    highlightthickness=1
                )
                option_menu.pack(fill=tk.X)
                self.input_fields[field["name"]] = {
                    "widget": var,
                    "type": "option",
                    "required": field.get("required", False)
                }

            elif field["type"] == "multiple":
                frame_check = tk.Frame(field_frame, bg=self.colors["white"])
                frame_check.pack(fill=tk.X)

                vars_check = []
                for j, option in enumerate(field["options"]):
                    var = tk.BooleanVar()
                    chk = tk.Checkbutton(
                        frame_check,
                        text=option,
                        variable=var,
                        bg=self.colors["white"],
                        fg=self.colors["text"],
                        font=self.fonts["small"],
                        selectcolor=self.colors["primary_red"],
                        highlightbackground=self.colors["border"],
                        highlightthickness=1
                    )
                    chk.grid(row=j // 5, column=j % 5, sticky=tk.W, padx=3, pady=1)
                    vars_check.append((option, var))

                self.input_fields[field["name"]] = {
                    "widget": vars_check,
                    "type": "multiple",
                    "required": field.get("required", False)
                }

        required_note = tk.Label(
            parent,
            text="* 为必填项",
            font=self.fonts["small"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        required_note.grid(row=(len(fields) - 1) // fields_per_row + 1, column=0,
                           columnspan=fields_per_row, sticky=tk.W, padx=10, pady=1)

    def validate_number(self, value):
        if value == "":
            return True
        try:
            float(value)
            return True
        except ValueError:
            return False

    def get_input_values(self):
        values = {}
        for name, field_info in self.input_fields.items():
            widget = field_info["widget"]
            field_type = field_info["type"]

            if field_type == "entry":
                value = widget.get().strip()
                if value:
                    try:
                        values[name] = float(value)
                    except ValueError:
                        values[name] = value
                else:
                    values[name] = None

            elif field_type == "option":
                values[name] = widget.get()

            elif field_type == "multiple":
                selected = [option for option, var in widget if var.get()]
                values[name] = selected

        return values

    def validate_inputs(self, values):
        for name, field_info in self.input_fields.items():
            if field_info["required"]:
                value = values.get(name)

                if value is None or value == "":
                    field_name = self._get_field_display_name(name)
                    messagebox.showerror("输入错误", f"请填写完整信息: {field_name}")
                    return False

                if field_info["type"] == "multiple" and not value:
                    field_name = self._get_field_display_name(name)
                    messagebox.showerror("输入错误", f"请至少选择一项: {field_name}")
                    return False
        return True

    def _get_field_display_name(self, name):
        field_names = {
            "age": "年龄",
            "amount": "保险金额",
            "gender": "性别",
            "occupation": "职业",
            "term": "保险期限",
            "smoker": "是否吸烟",
            "health": "健康状况",
            "property_type": "财产类型",
            "value": "财产估值",
            "location": "所在地区",
            "construction_year": "建筑年代",
            "coverage": "保障范围",
            "medical_history": "既往病史",
            "social_security": "是否有社保",
            "car_type": "车辆类型",
            "price": "购置价格",
            "car_age": "使用年限",
            "usage": "车辆用途",
            "owner_age": "车主年龄",
            "driving_years": "驾驶年限",
            "claims": "近3年理赔次数"
        }
        return field_names.get(name, name)

    def calculate_premium(self):
        values = self.get_input_values()

        if not self.validate_inputs(values):
            return

        insurance_type = self.selected_insurance.get()
        result = f"{insurance_type}保费评估结果：\n\n"

        if insurance_type == "人寿险":
            base_premium = values["amount"] * 10
            age_factor = min(1 + (values["age"] - 30) * 0.01, 2.5)
            occupation_factors = {"办公室职员": 1.0, "销售": 1.1, "体力劳动者": 1.3, "高空作业": 1.8, "危险行业": 2.0}
            occupation_factor = occupation_factors[values["occupation"]]
            smoker_factor = 1.5 if values["smoker"] == "是" else 1.0
            health_factors = {"优秀": 0.9, "良好": 1.0, "一般": 1.2, "较差": 1.5, "有既往病史": 2.0}
            health_factor = health_factors[values["health"]]

            term_factor = 1.0
            if values["term"] == "10":
                term_factor = 1.0
            elif values["term"] == "20":
                term_factor = 0.9
            elif values["term"] == "30":
                term_factor = 0.8
            elif values["term"] == "至60岁":
                term_factor = 0.85
            elif values["term"] == "至70岁":
                term_factor = 0.75
            elif values["term"] == "终身":
                term_factor = 0.7

            final_premium = base_premium * age_factor * occupation_factor * smoker_factor * health_factor * term_factor
            result += f"基础保费: {base_premium:.2f}元\n"
            result += f"年龄系数: {age_factor:.2f}\n"
            result += f"职业系数: {occupation_factor:.2f}\n"
            result += f"吸烟系数: {smoker_factor:.2f}\n"
            result += f"健康系数: {health_factor:.2f}\n"
            result += f"期限系数: {term_factor:.2f}\n"
            result += f"\n估算年保费: {final_premium:.2f}元"

        elif insurance_type == "健康险":
            base_premium = values["amount"] * 8
            age_factor = min(1 + (values["age"] - 30) * 0.02, 3.0)
            occupation_factors = {"办公室职员": 1.0, "销售": 1.1, "体力劳动者": 1.3, "高空作业": 1.8, "危险行业": 2.0}
            occupation_factor = occupation_factors[values["occupation"]]
            medical_factors = {"无": 1.0, "轻微疾病": 1.3, "慢性疾病": 1.8, "重大疾病史": 3.0}
            medical_factor = medical_factors[values["medical_history"]]
            social_security_factor = 0.8 if values["social_security"] == "有" else 1.0

            coverage_factor = 1.0 + (len(values["coverage"]) - 1) * 0.2

            final_premium = base_premium * age_factor * occupation_factor * medical_factor * social_security_factor * coverage_factor
            result += f"基础保费: {base_premium:.2f}元\n"
            result += f"年龄系数: {age_factor:.2f}\n"
            result += f"职业系数: {occupation_factor:.2f}\n"
            result += f"健康系数: {medical_factor:.2f}\n"
            result += f"社保系数: {social_security_factor:.2f}\n"
            result += f"保障范围系数: {coverage_factor:.2f}\n"
            result += f"\n估算年保费: {final_premium:.2f}元"

        elif insurance_type == "财产险":
            base_premium = values["value"] * 0.001 * 10000
            location_factors = {"一线城市": 1.2, "二线城市": 1.0, "三线城市": 0.9, "四线及以下城市": 0.8,
                                "农村地区": 1.1}
            location_factor = location_factors[values["location"]]
            construction_factors = {"5年以内": 0.8, "5-10年": 1.0, "10-20年": 1.3, "20年以上": 1.6}
            construction_factor = construction_factors[values["construction_year"]]

            coverage_factor = 1.0 + (len(values["coverage"]) - 1) * 0.3

            final_premium = base_premium * location_factor * construction_factor * coverage_factor
            result += f"基础保费: {base_premium:.2f}元\n"
            result += f"地区系数: {location_factor:.2f}\n"
            result += f"建筑年代系数: {construction_factor:.2f}\n"
            result += f"保障范围系数: {coverage_factor:.2f}\n"
            result += f"\n估算年保费: {final_premium:.2f}元"

        elif insurance_type == "车险":
            base_premium = values["price"] * 0.01 * 10000
            car_age_factor = min(1 + values["car_age"] * 0.05, 2.0)
            usage_factors = {"私家车": 1.0, "公务车": 1.2, "营运车辆": 1.8}
            usage_factor = usage_factors[values["usage"]]

            owner_age_factor = 1.0
            if values["owner_age"] < 25:
                owner_age_factor = 1.5
            elif values["owner_age"] >= 60:
                owner_age_factor = 1.3

            driving_factor = 1.0
            if values["driving_years"] < 2:
                driving_factor = 1.5
            elif values["driving_years"] < 5:
                driving_factor = 1.2

            claims_factors = {"0次": 0.8, "1次": 1.0, "2次": 1.2, "3次及以上": 1.5}
            claims_factor = claims_factors[values["claims"]]

            final_premium = base_premium * car_age_factor * usage_factor * owner_age_factor * driving_factor * claims_factor
            result += f"基础保费: {base_premium:.2f}元\n"
            result += f"车龄系数: {car_age_factor:.2f}\n"
            result += f"用途系数: {usage_factor:.2f}\n"
            result += f"车主年龄系数: {owner_age_factor:.2f}\n"
            result += f"驾龄系数: {driving_factor:.2f}\n"
            result += f"理赔次数系数: {claims_factor:.2f}\n"
            result += f"\n估算年保费: {final_premium:.2f}元"

        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, result)
        self.result_text.config(state=tk.DISABLED)


class MortgageCalculator:
    def __init__(self, parent, app):
        self.app = app
        self.frame = tk.Frame(parent, bg="#ffffff")

        self.colors = {
            "primary_red": "#DB0011",
            "secondary_red": "#E60028",
            "light_red": "#FFF0F0",
            "white": "#ffffff",
            "text": "#333333",
            "border": "#DB0011",
            "gray": "#F5F5F5"
        }

        self.fonts = {
            "title": ("Arial", 16, "bold"),
            "subtitle": ("Arial", 11, "bold"),
            "normal": ("Arial", 10),
            "small": ("Arial", 9)
        }

        self.main_frame = tk.Frame(self.frame, bg=self.colors["white"],
                                   highlightbackground=self.colors["border"],
                                   highlightthickness=1)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=2)

        # 添加返回按钮到左上角
        back_btn = tk.Button(
            self.main_frame,
            text="返回主页面",
            command=self.app.show_main_page,
            bg=self.colors["light_red"],
            fg=self.colors["primary_red"],
            font=self.fonts["small"],
            padx=5,
            pady=1
        )
        back_btn.pack(side=tk.TOP, anchor=tk.NW, padx=5, pady=5)

        # 创建logo，Antinio.Chan（AC）
        logo_frame = tk.Frame(self.main_frame, width=500, height=1, bg=self.colors["white"])
        logo_frame.pack(side=tk.RIGHT, anchor=tk.NE,padx=(1, 0), pady=1)

        canvas = tk.Canvas(logo_frame, width=100, height=80, bg=self.colors["white"], highlightthickness=0)
        canvas.pack(fill=tk.BOTH, expand=True)

        center_x, center_y = 40, 30
        radius = 25

        points = []
        for i in range(6):
            angle_rad = math.pi / 3 * (i + 0.5)
            x = center_x + radius * math.cos(angle_rad)
            y = center_y + radius * math.sin(angle_rad)
            points.append(x)
            points.append(y)

        canvas.create_polygon(points, fill=self.colors["primary_red"], outline="", width=2)
        canvas.create_text(center_x, center_y, text="A.C", fill=self.colors["white"],
                           font=("Arial", 12, "bold"))

        # 创建标题
        title_label = tk.Label(
            self.main_frame,
            text="房贷计算器",
            font=self.fonts["title"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        title_label.pack(pady=10)


        # 创建输入区域
        self.input_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        self.input_frame.pack(fill=tk.X, padx=20, pady=10)

        # 创建房贷计算所需的输入字段
        self.create_mortgage_fields()

        # 创建计算按钮
        self.calculate_btn = tk.Button(
            self.main_frame,
            text="计算房贷",
            command=self.calculate_mortgage,
            bg=self.colors["primary_red"],
            fg=self.colors["white"],
            font=self.fonts["subtitle"],
            padx=15,
            pady=1,
            relief=tk.RAISED,
            bd=1
        )
        self.calculate_btn.pack(pady=10)

        # 创建结果区域
        self.result_frame = tk.LabelFrame(
            self.main_frame,
            text="房贷计算结果",
            bg=self.colors["white"],
            fg=self.colors["primary_red"],
            font=self.fonts["subtitle"],
            highlightbackground=self.colors["border"],
            highlightthickness=1,
            bd=0
        )
        self.result_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)

        self.result_text = scrolledtext.ScrolledText(
            self.result_frame,
            bg=self.colors["white"],
            font=self.fonts["normal"],
            wrap=tk.WORD,
            relief=tk.FLAT,
            highlightthickness=0,
            padx=15,
            pady=1
        )
        self.result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=1)
        self.result_text.insert(tk.END, "请填写房贷信息，然后点击'计算房贷'按钮查看结果...")
        self.result_text.config(state=tk.DISABLED)

    def create_mortgage_fields(self):
        # 贷款金额
        tk.Label(
            self.input_frame,
            text="贷款金额(万元): *",
            font=self.fonts["normal"],
            bg=self.colors["white"],
            fg=self.colors["text"],
            anchor=tk.W
        ).grid(row=0, column=0, sticky=tk.W, padx=10, pady=10)

        self.loan_amount = tk.Entry(
            self.input_frame,
            font=self.fonts["normal"],
            width=20,
            highlightbackground=self.colors["border"],
            highlightthickness=1
        )
        self.loan_amount.grid(row=0, column=1, sticky=tk.W, padx=10, pady=10)
        validate_cmd = (self.frame.register(self.validate_number), '%P')
        self.loan_amount.config(validate="key", validatecommand=validate_cmd)

        # 贷款期限
        tk.Label(
            self.input_frame,
            text="贷款期限(年): *",
            font=self.fonts["normal"],
            bg=self.colors["white"],
            fg=self.colors["text"],
            anchor=tk.W
        ).grid(row=1, column=0, sticky=tk.W, padx=10, pady=10)

        self.loan_term = tk.Entry(
            self.input_frame,
            font=self.fonts["normal"],
            width=20,
            highlightbackground=self.colors["border"],
            highlightthickness=1
        )
        self.loan_term.grid(row=1, column=1, sticky=tk.W, padx=10, pady=10)
        self.loan_term.config(validate="key", validatecommand=validate_cmd)

        # 年利率
        tk.Label(
            self.input_frame,
            text="年利率(%): *",
            font=self.fonts["normal"],
            bg=self.colors["white"],
            fg=self.colors["text"],
            anchor=tk.W
        ).grid(row=2, column=0, sticky=tk.W, padx=10, pady=10)

        self.interest_rate = tk.Entry(
            self.input_frame,
            font=self.fonts["normal"],
            width=20,
            highlightbackground=self.colors["border"],
            highlightthickness=1
        )
        self.interest_rate.grid(row=2, column=1, sticky=tk.W, padx=10, pady=10)
        self.interest_rate.config(validate="key", validatecommand=validate_cmd)

        # 还款方式
        tk.Label(
            self.input_frame,
            text="还款方式: *",
            font=self.fonts["normal"],
            bg=self.colors["white"],
            fg=self.colors["text"],
            anchor=tk.W
        ).grid(row=3, column=0, sticky=tk.W, padx=10, pady=10)

        self.repayment_method = tk.StringVar()
        self.repayment_method.set("等额本息")
        repayment_options = ["等额本息", "等额本金"]

        repayment_menu = tk.OptionMenu(
            self.input_frame,
            self.repayment_method,
            *repayment_options
        )
        repayment_menu.config(
            font=self.fonts["normal"],
            width=18,
            bg=self.colors["white"],
            activebackground=self.colors["light_red"],
            highlightbackground=self.colors["border"],
            highlightthickness=1
        )
        repayment_menu.grid(row=3, column=1, sticky=tk.W, padx=10, pady=10)

    def validate_number(self, value):
        if value == "":
            return True
        try:
            float(value)
            return True
        except ValueError:
            return False

    def calculate_mortgage(self):
        try:
            loan_amount = float(self.loan_amount.get()) * 10000  # 转换为元
            loan_term = int(self.loan_term.get())
            interest_rate = float(self.interest_rate.get()) / 100  # 转换为小数
            repayment_method = self.repayment_method.get()

            if loan_amount <= 0 or loan_term <= 0 or interest_rate <= 0:
                messagebox.showerror("输入错误", "请输入有效的数值（必须大于0）")
                return

        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数值")
            return

        monthly_rate = interest_rate / 12
        total_months = loan_term * 12

        result = "房贷计算结果：\n\n"
        result += f"贷款金额：{loan_amount / 10000:.2f}万元\n"
        result += f"贷款期限：{loan_term}年（{total_months}个月）\n"
        result += f"年利率：{interest_rate * 100:.2f}%\n"
        result += f"还款方式：{repayment_method}\n\n"

        if repayment_method == "等额本息":
            monthly_payment = loan_amount * monthly_rate * (1 + monthly_rate) ** total_months / \
                              ((1 + monthly_rate) ** total_months - 1)
            total_payment = monthly_payment * total_months
            total_interest = total_payment - loan_amount

            result += f"每月还款：{monthly_payment:.2f}元\n"
            result += f"总还款金额：{total_payment:.2f}元\n"
            result += f"总支付利息：{total_interest:.2f}元\n"

        else:  # 等额本金
            principal_payment = loan_amount / total_months
            total_payment = 0

            result += "首月还款："
            first_month_interest = loan_amount * monthly_rate
            first_month_payment = principal_payment + first_month_interest
            result += f"{first_month_payment:.2f}元\n"

            result += "末月还款："
            last_month_interest = principal_payment * monthly_rate
            last_month_payment = principal_payment + last_month_interest
            result += f"{last_month_payment:.2f}元\n"

            total_payment = (first_month_payment + last_month_payment) * total_months / 2
            total_interest = total_payment - loan_amount

            result += f"总还款金额：{total_payment:.2f}元\n"
            result += f"总支付利息：{total_interest:.2f}元\n"

        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, result)
        self.result_text.config(state=tk.DISABLED)


if __name__ == "__main__":
    root = tk.Tk()
    app = CalculatorApp(root)
    root.mainloop()